const mongoose = require('mongoose');
const { User } = require('../models/User');
const { Post } = require('../models/Post');
const { Category } = require('../models/Category');
const { Comment } = require('../models/Comment');
const { users } = require('../models/User');
const { posts } = require('../models/Post');
const { categories } = require('../models/Category');
const { comments } = require('../models/Comment');

// 数据库配置
const dbConfig = {
  // 本地 MongoDB 连接字符串
  localUrl: 'mongodb://localhost:27017/blogdb',
  
  // 如果MongoDB未运行，使用内存数据的降级选项
  useInMemory: false,
  
  // 数据库选项
  options: {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }
};

// 连接数据库
const connectDB = async () => {
  try {
    const conn = await mongoose.connect(dbConfig.localUrl, dbConfig.options);
    console.log(`MongoDB 连接成功: ${conn.connection.host}`);
    dbConfig.useInMemory = false;
    
    // 初始化数据库数据
    await initializeDatabase();
  } catch (error) {
    console.error(`数据库连接失败: ${error.message}`);
    console.log('将使用内存数据模式');
    dbConfig.useInMemory = true;
  }
};

// 初始化数据库数据
const initializeDatabase = async () => {
  try {
    // 检查是否需要初始化数据
    const userCount = await User.countDocuments();
    const postCount = await Post.countDocuments();
    const categoryCount = await Category.countDocuments();
    const commentCount = await Comment.countDocuments();
    
    if (userCount === 0 && postCount === 0 && categoryCount === 0 && commentCount === 0) {
      console.log('数据库为空，正在初始化示例数据...');
      
      // 插入分类数据（如果categories数组存在）
      let categoryDocs = [];
      if (categories && Array.isArray(categories)) {
        categoryDocs = await Category.insertMany(categories.map(cat => ({
          _id: cat.id,
          name: cat.name,
          description: cat.description
        })));
        console.log(`已插入 ${categoryDocs.length} 个分类`);
      }
      
      // 插入用户数据（如果users数组存在）
      let userDocs = [];
      if (users && Array.isArray(users)) {
        userDocs = await User.insertMany(users.map(user => ({
          _id: user.id,
          name: user.name,
          email: user.email
        })));
        console.log(`已插入 ${userDocs.length} 个用户`);
      }
      
      // 插入文章数据（如果posts数组存在）
      let postDocs = [];
      if (posts && Array.isArray(posts)) {
        postDocs = await Post.insertMany(posts.map(post => ({
          _id: post.id,
          title: post.title,
          content: post.content,
          author: post.author,
          categoryId: post.categoryId,
          createdAt: post.createdAt,
          updatedAt: post.updatedAt
        })));
        console.log(`已插入 ${postDocs.length} 篇文章`);
      }
      
      // 插入评论数据（如果comments数组存在）
      let commentDocs = [];
      if (comments && Array.isArray(comments)) {
        commentDocs = await Comment.insertMany(comments.map(comment => ({
          _id: comment.id,
          content: comment.content,
          author: comment.author,
          postId: comment.postId,
          createdAt: comment.createdAt
        })));
        console.log(`已插入 ${commentDocs.length} 条评论`);
      }
      
      console.log('示例数据初始化完成');
    } else {
      console.log('数据库中已有数据，跳过初始化');
    }
  } catch (error) {
    console.error('初始化数据库时出错:', error);
  }
};

module.exports = {
  connectDB,
  dbConfig
};